package cn.stylefeng.guns.modular.order.service.impl;

import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.core.util.justCgrkApi;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.order.entity.OrderPut;
import cn.stylefeng.guns.modular.order.entity.OrderPutDetailed;
import cn.stylefeng.guns.modular.order.entity.OrderPutExcelItem;
import cn.stylefeng.guns.modular.order.model.params.OrderPutParam;
import cn.stylefeng.guns.modular.order.service.*;
import cn.stylefeng.guns.modular.storage.service.StorageOutService;
import cn.stylefeng.guns.modular.storage.service.StoragePutSingleService;
import cn.stylefeng.guns.modular.storage.service.impl.StorageOutDetailedServiceImpl;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * 聚水潭入库订单
 * </p>
 *
 * @author wp
 * @since 2025-06-09
 */
@Service
public class JSTPutOrderScheduledServiceImpl implements JSTPutOrderScheduledService {


    private Lock lock = new ReentrantLock();
    @Autowired
    private BasicCustomerService basicCustomerService;
    @Autowired
    private OutOrderService outOrderService ;
    @Autowired
    private UserService userService;
    @Autowired
    private OutOrderDetailedService outOrderDetailedService;
    @Autowired
    private StorageOutService storageOutService;
    @Autowired
    private StorageOutDetailedServiceImpl storageOutDetailedService;
    @Autowired
    private OrderTransportService orderTransportService;
    @Autowired
    private OrderPutService orderPutService;
    @Autowired
    private OrderPutDetailedService orderPutDetailedService;
    @Autowired
    private StoragePutSingleService storagePutSingleService;


    @Override
    public ResponseData getJSTPutOrder(Long userId,Long customerId)  {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String modified_end = now.format(formatter);

        // 减去20分钟
        LocalDateTime tenMinutesAgo = now.minus(Duration.ofHours(10));
        String modified_begin = tenMinutesAgo.format(formatter);
        Date date = null;
        Date date2 = null;
        try {
            date = sdf.parse(modified_begin);
            date2 = sdf.parse(modified_end);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        User user = userService.getById(userId);

        if(DateUtil.differentDaysByMillisecond(date, date2) > 7) {
            return ResponseData.error("时间不能超过7天");
        }
        ResponseData resdata = new ResponseData();
        resdata.setSuccess(true);
        BasicCustomer basicCustomer = basicCustomerService.getById(customerId);
        if(ToolUtil.isEmpty(basicCustomer.getJustAppkey())) {
            return ResponseData.error("请添加基础信息客户聚水潭appKey");
        }
        if(ToolUtil.isEmpty(basicCustomer.getJustAppsecret())) {
            return ResponseData.error("请添加基础信息客户聚水潭appSecret");
        }
        if(ToolUtil.isEmpty(basicCustomer.getAccessToken())) {
            return ResponseData.error("请添加基础信息客户聚水潭客户授权码");
        }


        Integer page_index = 1;//页数
        boolean has_next = true;//是否有下一页
        while (has_next) {

            //只能分页查询，一页最多50条
            //接口调用频率秒级内不超过5次，分钟内不超过100次
            String data = null;
            try {
                data = justCgrkApi.getSellerItemNew(basicCustomer.getJustAppkey(),
                        basicCustomer.getJustAppsecret(),
                        basicCustomer.getAccessToken(),
                        modified_begin,
                        modified_end,
                        page_index.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
            org.json.JSONObject jsonObject = new org.json.JSONObject(data);
            if(jsonObject.get("code").toString().equals("0")) {
                org.json.JSONObject jsonObject1 = new org.json.JSONObject(jsonObject.get("data").toString());
                if(Integer.parseInt(jsonObject1.get("data_count").toString()) > 0) {
                    if(jsonObject1.get("has_next").toString().equals("false")) {
                        has_next = false;
                    }
                    JSONArray jsonArray = new JSONArray(jsonObject1.get("datas").toString());
                    List<OrderPutExcelItem> list = new ArrayList<OrderPutExcelItem>();
                    List<OrderPutExcelItem> list1 = new ArrayList<OrderPutExcelItem>();
                    for (Object object : jsonArray) {

                        org.json.JSONObject jsonObject2 = new org.json.JSONObject(object.toString());

                        if(14648074 !=jsonObject2.getInt("wms_co_id")){
                            continue;
                        }
                        if("大坝".equals(jsonObject2.getString("supplier_name"))){
                            continue;
                        }
                        String type = jsonObject2.getString("type");
                        System.err.println(type);
                        String io_id = jsonObject2.get("io_id").toString().replace("null", "");//外部单号);//外部单号
                        JSONArray jsonArray1 = new JSONArray(jsonObject2.get("items").toString());
                        JSONArray batchsJsonArray = new JSONArray(jsonObject2.get("batchs").toString());
                        jsonArray1.forEach(item ->{
                            cn.hutool.json.JSONObject jsonObjectitem = new cn.hutool.json.JSONObject(item.toString());
                            OrderPutExcelItem excelItem = new OrderPutExcelItem();
                            excelItem.setShipmentnumber(io_id);
                            String sku_id = jsonObjectitem.get("sku_id").toString();//商品编码
                            excelItem.setGoodsNumber(sku_id);

                            String name = jsonObjectitem.get("name").toString();//商品名称
                            excelItem.setGoodsName(name);
                            batchsJsonArray.forEach(batch -> {
                                cn.hutool.json.JSONObject bajsonObject = new cn.hutool.json.JSONObject(batch.toString());
                                if (bajsonObject.getStr("sku_id").equals(jsonObjectitem.getStr("sku_id"))) {
                                    excelItem.setGoodsbatchs(bajsonObject.getStr("batch_no"));
                                    excelItem.setBatchnumber(bajsonObject.getStr("product_date"));
                                }
                            });
                            String qty = jsonObjectitem.get("qty").toString();//入库数量
                            excelItem.setPutnum(qty);
                            if("采购进仓".equals(type)){
                                list.add(excelItem);
                            }

                        });
                        if(list.size()>0) {
                            OrderPutParam orderPutParam = new OrderPutParam();
                            orderPutParam.setPutCustomerId(customerId);
                            orderPutParam.setWarehouseId(96L);

                            orderPutService.savePulljstputorder(user,orderPutParam,list);
                        }
                    }

                } else {
                    has_next = false;
                    resdata.setSuccess(false);
                    resdata.setMessage("未获取到快递明细");
                }
            } else {
                has_next = false;
                resdata.setSuccess(false);
                resdata.setMessage("拉取失败！"+data);
            }
            page_index++;
            if(has_next) {
                try {
                    Thread.currentThread().sleep(650);//如果有下一页 等待0.65秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


        }

        return resdata;
    }

    @Override
    public ResponseData submitJSTPutOrderNew(long[] ids,User user) {
        ResponseData data = new ResponseData();
        lock.lock();//获取锁

        try {
            //批量生成入库单 ，托盘，货运单
            for (Long id :ids) {
                //判断明细是否添加了
                OrderPut orderPut = orderPutService.getById(id);
                if ("待提交".equals(orderPut.getBillstate())||"撤回".equals(orderPut.getBillstate())) {
                    QueryWrapper<OrderPutDetailed> queryWrapper = new QueryWrapper<OrderPutDetailed>();
                    queryWrapper.eq("put_detailed_number", orderPut.getPutNumber());
                    int count = orderPutDetailedService.count(queryWrapper);
                    if (count>0) {
                        storagePutSingleService.productionPutSingleNew(orderPut ,user);
                    } else {
                        data.setSuccess(false);
                        data.setMessage("请先添加商品明细");
                        return data;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
        return data;
    }

    @Override
    public ResponseData getJSTPutOrderWh(Long userId, Long customerId) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String modified_end = now.format(formatter);

        // 减去20分钟
        LocalDateTime tenMinutesAgo = now.minus(Duration.ofHours(10));
        String modified_begin = tenMinutesAgo.format(formatter);
        Date date = null;
        Date date2 = null;
        try {
            date = sdf.parse(modified_begin);
            date2 = sdf.parse(modified_end);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        User user = userService.getById(userId);

        if(DateUtil.differentDaysByMillisecond(date, date2) > 7) {
            return ResponseData.error("时间不能超过7天");
        }
        ResponseData resdata = new ResponseData();
        resdata.setSuccess(true);
        BasicCustomer basicCustomer = basicCustomerService.getById(customerId);
        if(ToolUtil.isEmpty(basicCustomer.getJustAppkey())) {
            return ResponseData.error("请添加基础信息客户聚水潭appKey");
        }
        if(ToolUtil.isEmpty(basicCustomer.getJustAppsecret())) {
            return ResponseData.error("请添加基础信息客户聚水潭appSecret");
        }
        if(ToolUtil.isEmpty(basicCustomer.getAccessToken())) {
            return ResponseData.error("请添加基础信息客户聚水潭客户授权码");
        }


        Integer page_index = 1;//页数
        boolean has_next = true;//是否有下一页
        while (has_next) {

            //只能分页查询，一页最多50条
            //接口调用频率秒级内不超过5次，分钟内不超过100次
            String data = null;
            try {
                data = justCgrkApi.getSellerItemNew(basicCustomer.getJustAppkey(),
                        basicCustomer.getJustAppsecret(),
                        basicCustomer.getAccessToken(),
                        modified_begin,
                        modified_end,
                        page_index.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
            org.json.JSONObject jsonObject = new org.json.JSONObject(data);
            if(jsonObject.get("code").toString().equals("0")) {
                org.json.JSONObject jsonObject1 = new org.json.JSONObject(jsonObject.get("data").toString());
                if(Integer.parseInt(jsonObject1.get("data_count").toString()) > 0) {
                    if(jsonObject1.get("has_next").toString().equals("false")) {
                        has_next = false;
                    }
                    JSONArray jsonArray = new JSONArray(jsonObject1.get("datas").toString());
                    List<OrderPutExcelItem> list = new ArrayList<OrderPutExcelItem>();
                    List<OrderPutExcelItem> list1 = new ArrayList<OrderPutExcelItem>();
                    for (Object object : jsonArray) {

                        org.json.JSONObject jsonObject2 = new org.json.JSONObject(object.toString());

                        if(15260317 !=jsonObject2.getInt("wms_co_id")){
                            continue;
                        }
                        if("大坝".equals(jsonObject2.getString("supplier_name"))){
                            continue;
                        }
                        String type = jsonObject2.getString("type");
                        System.err.println(type);
                        String io_id = jsonObject2.get("io_id").toString().replace("null", "");//外部单号);//外部单号
                        JSONArray jsonArray1 = new JSONArray(jsonObject2.get("items").toString());
                        JSONArray batchsJsonArray = new JSONArray(jsonObject2.get("batchs").toString());
                        jsonArray1.forEach(item ->{
                            cn.hutool.json.JSONObject jsonObjectitem = new cn.hutool.json.JSONObject(item.toString());
                            OrderPutExcelItem excelItem = new OrderPutExcelItem();
                            excelItem.setShipmentnumber(io_id);
                            String sku_id = jsonObjectitem.get("sku_id").toString();//商品编码
                            excelItem.setGoodsNumber(sku_id);

                            String name = jsonObjectitem.get("name").toString();//商品名称
                            excelItem.setGoodsName(name);
                            batchsJsonArray.forEach(batch -> {
                                cn.hutool.json.JSONObject bajsonObject = new cn.hutool.json.JSONObject(batch.toString());
                                if (bajsonObject.getStr("sku_id").equals(jsonObjectitem.getStr("sku_id"))) {
                                    excelItem.setGoodsbatchs(bajsonObject.getStr("batch_no"));
                                    excelItem.setBatchnumber(bajsonObject.getStr("product_date"));
                                }
                            });
                            String qty = jsonObjectitem.get("qty").toString();//入库数量
                            excelItem.setPutnum(qty);
                            if("采购进仓".equals(type)){
                                list.add(excelItem);
                            }

                        });
                        if(list.size()>0) {
                            OrderPutParam orderPutParam = new OrderPutParam();
                            orderPutParam.setPutCustomerId(customerId);
                            orderPutParam.setWarehouseId(122L);

                            orderPutService.savePulljstputorder(user,orderPutParam,list);
                        }
                    }

                } else {
                    has_next = false;
                    resdata.setSuccess(false);
                    resdata.setMessage("未获取到快递明细");
                }
            } else {
                has_next = false;
                resdata.setSuccess(false);
                resdata.setMessage("拉取失败！"+data);
            }
            page_index++;
            if(has_next) {
                try {
                    Thread.currentThread().sleep(650);//如果有下一页 等待0.65秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


        }

        return resdata;

    }


    public static void main(String[] args) {

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String nowStr = now.format(formatter);
        System.out.println(nowStr);

        // 减去10分钟
        LocalDateTime tenMinutesAgo = now.minus(Duration.ofMinutes(10));
        String tenMinutesAgoStr = tenMinutesAgo.format(formatter);
        System.out.println(tenMinutesAgoStr);

    }
}
